package mysql

import (
	"api/global"
	"api/model"

	"gorm.io/gorm"
)

func GetUser(query interface{}, args ...interface{}) (*model.User, error) {
	var user model.User
	err := global.DBHandle.Where(query, args...).First(&user).Error
	if err != nil {
		return nil, err
	}

	return &user, nil
}

func GetUsers(offset int, limit int, selects []string, query interface{}, args ...interface{}) (*[]model.ResponseUsersDataData, int64, error) {
	var users []model.ResponseUsersDataData
	var total int64
	var db *gorm.DB = global.DBHandle.Model(&model.User{})
	err := db.Where(query, args...).Count(&total).Error
	if err != nil {
		return nil, 0, err
	}
	err = db.Where(query, args...).Select(selects).Limit(limit).Offset(offset).Find(&users).Error
	if err != nil {
		return nil, 0, err
	}
	return &users, total, nil
}

func AddUser(user *model.User) (string, error) {
	err := global.DBHandle.Create(user).Error
	if err != nil {
		return "", err
	}
	return user.Id, nil
}
